package com.sync.data.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateProperties;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.util.Map;
import java.util.Objects;

/**
 * @description: 体系管理的repository配置
 * @Date: 2020/11/11 14:25
 */
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        basePackages = "com.sync.data.mce.repository",
        entityManagerFactoryRef="entityManagerFactoryMce",
        transactionManagerRef="transactionManagerMce")
public class MceRepositoryConfig {

    @Autowired
    @Qualifier("mceDataSource")
    private DataSource mceDataSource;

    @Autowired
    private JpaProperties jpaProperties;

    @Autowired
    private HibernateProperties hibernateProperties;

    /**
     * @param builder
     * @return
     */
    @Bean(name = "entityManagerFactoryMce")
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryMce(
            EntityManagerFactoryBuilder builder) {
        Map<String, Object> properties = hibernateProperties.determineHibernateProperties(
                jpaProperties.getProperties(), new HibernateSettings());
        return builder.dataSource(mceDataSource).properties(properties)
                .persistenceUnit("mce")
                .packages("com.sync.data.mce.entity").build();
    }


    @Bean(name = "transactionManagerMce")
    public PlatformTransactionManager transactionManagerMce(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(Objects.requireNonNull(entityManagerFactoryMce(builder).getObject()));
    }
}
